package com.mediacloud.app.newsmodule.fragment.military

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.haibin.calendarview.Calendar
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.util.getArticleLogoUrl
import com.mediacloud.app.assembly.util.load
import com.mediacloud.app.assembly.util.loadX
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.fragment.BaseFragment
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.imagetext.CalendarImageTextDetailFragment
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.util.TimeUtils
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.aappfactory_fragment_military_calendar2.*
import org.json.JSONObject
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*

class MilitaryCalendarFragment2 : HqyNavFragment() {
    var catalogID: String? = null
    var adapter: Adapter? = null

    var sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
    val sdf1 = SimpleDateFormat("yyyy.MM月", Locale.CHINA)
    protected var catalogItem: CatalogItem? = null
    private val indicatorViews: MutableList<View?> = ArrayList()
    var sheet: MilitaryCalendarSheet? = null
    var year = 0
    var month = 0
    var day = 0

    //var currentIndex = 0
    var todayStamp: Long = 0L
    var targetIndex = 0
    var starTime = 0L
    var endTime = 0L
    var targetTime = 0L
    override fun getLayoutResID(): Int {
        return R.layout.aappfactory_fragment_military_calendar2
    }

    override fun initView() {
        val calendar = java.util.Calendar.getInstance()
        calendar.time = Date()

    }

    override fun initArgs() {
        super.initArgs()
        navPaddingTopMatch()

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        rootLayout.setBackgroundColor(Color.TRANSPARENT)

        loadingView = findViewById(R.id.mLoadingView)
        initStateView()
        catalogID = arguments?.getString("id")
        catalogItem = arguments?.getParcelable("catalog")

        recyclerView.layoutManager = CenterLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        val singleWidth = resources.getDimensionPixelSize(R.dimen.dimen40)
        val totalWidth = singleWidth * 7
        val itemDecorationWidth = (Utility.getScreenWidth(context) - 2 * resources.getDimensionPixelSize(R.dimen.dimen15) - totalWidth) / 6
        val itemDecoration = DividerItemDecoration(requireContext(), LinearLayoutManager.HORIZONTAL)
        val drawable = GradientDrawable()
        drawable.setSize(itemDecorationWidth, resources.getDimensionPixelSize(R.dimen.dimen100))
        drawable.setColor(Color.TRANSPARENT)
        itemDecoration.setDrawable(drawable)
        recyclerView.addItemDecoration(itemDecoration)
        adapter = Adapter(requireContext())
        recyclerView.adapter = adapter

        initBanner()
        val data = arguments?.getParcelable<ArticleItem>("DATA")

        val todayStr = sdf.format(System.currentTimeMillis());
        todayStamp = sdf.parse(todayStr).time
        endTime = todayStamp
        starTime = todayStamp - 31 * 3600 * 1000 * 24L
        data?.let {
            val targetData = sdf.parse(data.publishdate)
            val calendar = java.util.Calendar.getInstance()
            buildTime(targetData.time)
            calendar.time = targetData
            year = calendar.get(java.util.Calendar.YEAR)
            month = calendar.get(java.util.Calendar.MONTH)+1
            day = calendar.get(java.util.Calendar.DAY_OF_MONTH)
        }
        getCalendarData()
        adapter?.setOnItemClickListener { adapter, view, position ->
            val data = adapter.data.get(position) as MilitaryCalendarData
            try {
                val date=sdf.parse(data.date)
                dateTv.text = sdf1.format(date)
                val calendar = java.util.Calendar.getInstance()
                calendar.time = date
                year = calendar.get(java.util.Calendar.YEAR)
                month = calendar.get(java.util.Calendar.MONTH)+1
                day = calendar.get(java.util.Calendar.DAY_OF_MONTH)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            if (data.data.isNullOrEmpty()) {
                // banner.visibility = View.GONE
                return@setOnItemClickListener
            } else {
                banner.visibility = View.VISIBLE
            }
            data.data?.let {
                this.adapter?.selectedPosition = position
                this.adapter?.notifyDataSetChanged()
                recyclerView.postDelayed({
                    recyclerView.smoothScrollToPosition(position)
                }, 300)
                setIndicatorViews(it)
            }
        }

        dateTv.text = sdf1.format(targetTime)
        dateTv.setOnClickListener {
            openDateSelector()
        }
        openIv.setOnClickListener {
            openDateSelector()
        }
    }


    private fun buildTime(targetTime: Long) {
        this.targetTime = targetTime
        // 如果目标日期+15天大于了今天 开始时间就取 今天往前推31天
        if (targetTime + 15 * 3600 * 1000 * 24L > todayStamp) {
            starTime = todayStamp - 31 * 3600 * 1000 * 24L
            //结束时间一定要多出3天 否则不能居中
            val tempEndTime = targetTime + 3 * 3600 * 1000 * 24L
            if (tempEndTime > todayStamp) {
                endTime = tempEndTime

            } else {
                endTime = todayStamp
            }
        } else {
            //这种情况前后取15天
            starTime = targetTime - 15 * 3600 * 1000 * 24L
            endTime = targetTime + 15 * 3600 * 1000 * 24L
        }
        targetIndex = ((targetTime - starTime) / (3600 * 1000 * 24L)).toInt()
    }

    private fun openDateSelector() {
        sheet = MilitaryCalendarSheet()
        val b = Bundle()
        b.putString("NID", catalogID)
        b.putInt("year", year)
        b.putInt("month", month)
        b.putInt("day", day)
        sheet!!.arguments = b
        sheet?.call = object : MilitaryCalendarSheet.SelectedCall {
            override fun onSelected(calendar: Calendar?) {
                calendar?.let {
                    year = it.year
                    month = it.month
                    day = it.day
                    buildTime(it.timeInMillis)
                    getCalendarData()
                    dateTv.text = sdf1.format(targetTime)
                }
            }
        }
        sheet?.show(childFragmentManager, "")
    }

    /**
     * 获取日历信息
     */
    private fun getCalendarData() {


        val d = DataInvokeUtil
            .ziMeiTiApi
            .getCalendarDate(catalogID, "${sdf.format(starTime)}", "${sdf.format(endTime)}", "1")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<Response<JSONObject>> {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(t: Response<JSONObject>) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    t.body()?.let {
                        if (it.optBoolean("state")) {

                            //val dataIndex = it.optInt("date_index")
                            val dataArray = it.optJSONArray("data")
                            val items: MutableList<MilitaryCalendarData> = ArrayList()
                            for (i in 0 until dataArray.length()) {
                                val item = MilitaryCalendarData()
                                val obj = dataArray.optJSONObject(i)
                                item.date = obj.optString("date")
                                item.week_no = obj.optString("week_no")
                                val chineseDate: MutableList<String> = ArrayList()
                                val chineseDateArrays = obj.optJSONArray("chinese_date")
                                for (k in 0 until chineseDateArrays.length()) {
                                    chineseDate.add(chineseDateArrays.optString(k))
                                }
                                item.chinese_date = chineseDate
                                val articles: MutableList<ArticleItem> = ArrayList()
                                val articleArrays = obj.optJSONArray("data")
                                for (k in 0 until articleArrays.length()) {
                                    articles.add(ArticleItem.parse(articleArrays.optJSONObject(k)))
                                }
                                item.data = articles
                                items.add(item)
                            }
                            //    adapter?.selectedPosition = dataIndex
                            items.reverse()
                            adapter?.setNewData(items)
                            if (targetIndex < items.size) {
                                val item = items[targetIndex]

//                                if (item.data.isNullOrEmpty()) {
//                                    val size = items.size
//                                    for (i in 0 until size) {
//                                        val temp = items[i]
//                                        if (temp.data != null && temp.data!!.size > 0) {
//                                            currentIndex = i
//                                            break
//                                        }
//                                    }
//                                }
                                items[targetIndex].data?.let {
                                    setIndicatorViews(it)
                                }
                                adapter?.selectedPosition = targetIndex
                                adapter?.notifyDataSetChanged()
                                recyclerView.postDelayed({
                                    if (recyclerView!=null) {
                                        recyclerView.smoothScrollToPosition(targetIndex)
                                    }
                                }, 300)
                            }

                        }
                    }
                }

                override fun onError(e: Throwable) {

                }

                override fun onComplete() {

                }
            })
    }

    var imageTextDetailFragment: CalendarImageTextDetailFragment? = null
    private fun setIndicatorViews(_items: MutableList<ArticleItem>) {
        val items: MutableList<ArticleItem> = ArrayList()
        if (_items.size > 0) {
            items.add(_items[0])
        }
        if (items.size > 0) {
            if (items[0].type == TypeX.NEWS.NEWS) {
                showStateView(TYPE_LOADING, false)
                imageTextDetailFragment = CalendarImageTextDetailFragment()
                val bundle = Bundle()
                bundle.putParcelable("data", items[0])
                bundle.putParcelable("catalog", catalogItem)
                bundle.putBoolean("IS_CALENDAR", true)
                imageTextDetailFragment?.arguments = bundle
                val manager = childFragmentManager
                val transaction = manager.beginTransaction()
                transaction.replace(R.id.container, imageTextDetailFragment!!)
                transaction.commitNowAllowingStateLoss()
            } else {
                imageTextDetailFragment?.let {
                    val manager = childFragmentManager
                    val transaction = manager.beginTransaction()
                    transaction.remove(it)
                    transaction.commitNowAllowingStateLoss()
                }
            }
        }

        indicatorViews.clear()

        indicatorContainer.removeAllViews()

        if (items.isNullOrEmpty()) {
            banner.visibility = View.GONE
            return
        } else {
            banner.visibility = View.VISIBLE
        }
        val dimen5 = resources.getDimensionPixelSize(R.dimen.dimen5)
        items?.forEachIndexed { index, articleItem ->
            val view = View(requireContext())
            view.background = ContextCompat.getDrawable(requireContext(), R.drawable.indicator_selector_x2)
            val lp: LinearLayout.LayoutParams = LinearLayout.LayoutParams(dimen5, dimen5)
            lp.marginStart = dimen5
            indicatorContainer.addView(view, lp)
            if (index == 0) {
                view.isSelected = true;
            }
            indicatorViews.add(view)
        }
        if (items.size > 0)
            banner.setBannerData(R.layout.military_banner_item, items)
        if (indicatorViews.size > 1) {
            banner.setAutoPlayAble(true)
            banner.setAllowUserScrollable(true)
            indicatorContainer.visibility = View.VISIBLE
            banner.startAutoPlay()
        } else {
            banner.setAutoPlayAble(false)
            banner.setAllowUserScrollable(false)
            // indicatorContainer.visibility = View.INVISIBLE
            indicatorContainer.visibility = View.GONE
        }


    }

    inner class Adapter(val context: Context) : BaseQuickAdapter<MilitaryCalendarData, BaseViewHolder>(R.layout.military_date_item) {
        var selectedPosition = 0;
        private val halfColor: Int = ContextCompat.getColor(context, R.color.color_half_white)
        private val themeColor: Int = ContextCompat.getColor(context, R.color.cctv7_red)

        override fun convert(helper: BaseViewHolder, item: MilitaryCalendarData) {
            val weekTv: TextView = helper.getView(R.id.weekTv)
            val dataTv: TextView = helper.getView(R.id.dateTv)
            val lDateTv: TextView = helper.getView(R.id.lDateTv)
            val cardView: View = helper.getView(R.id.cardView)
//            when (helper.absoluteAdapterPosition) {
//                0 -> {
//                    weekTv.text = "一"
//                }
//                1 -> {
//                    weekTv.text = "二"
//                }
//                2 -> {
//                    weekTv.text = "三"
//                }
//                3 -> {
//                    weekTv.text = "四"
//                }
//                4 -> {
//                    weekTv.text = "五"
//                }
//                5 -> {
//                    weekTv.text = "六"
//                }
//                else -> {
//                    weekTv.text = "日"
//                }
//            }
            weekTv.text = item.week_no
            try {
                dataTv.text = (item.date ?: "").split("-")[2]
            } catch (e: Exception) {
                dataTv.text = ""
                e.printStackTrace()
            }
            lDateTv.text = item.chinese_date?.get(2) ?: ""
            if (helper.absoluteAdapterPosition == selectedPosition) {
                cardView.background = ContextCompat.getDrawable(context, R.drawable.military_date_selected)
                dataTv.setTextColor(themeColor)
                lDateTv.setTextColor(themeColor)
                weekTv.setTextColor(Color.WHITE)
            } else {
                if (item.data == null || item.data!!.isEmpty()) {
                    weekTv.setTextColor(halfColor)
                    cardView.background = ContextCompat.getDrawable(context, R.drawable.military_date_disable)
                    dataTv.setTextColor(halfColor)
                    lDateTv.setTextColor(halfColor)
                } else {
                    weekTv.setTextColor(Color.WHITE)
                    cardView.background = ContextCompat.getDrawable(context, R.drawable.military_date_enable)
                    dataTv.setTextColor(Color.WHITE)
                    lDateTv.setTextColor(Color.WHITE)
                }
            }
        }
    }

    private fun initBanner() {
        banner.setAutoPlayAble(true)
        banner.setAutoPlayTime(3000) // 切换的时间
        banner.setHandLoop(true)
        banner.setPointsIsVisible(false);
        banner.loadImage { banner, model, view, position ->
            val articleItem = model as ArticleItem
            val logoIv = view.findViewById<ImageView>(R.id.logoIv)
            val titleTv = view.findViewById<TextView>(R.id.titleTv)
            val timeTv = view.findViewById<TextView>(R.id.timeTv)
            logoIv.loadX(getArticleLogoUrl(1, 1, articleItem), 2, 0, true, null)
            titleTv.text = articleItem.getTitle()
            timeTv.text = TimeUtils.originalTimeToEndDay(articleItem.publishdate)
        }
        banner.setOnItemClickListener { banner, model, view, position ->
            val articleItem = model as ArticleItem
            NewsItemClickUtils.OpenItemNewsHandle(requireContext(), articleItem.type, articleItem, catalogItem)
        }
        banner.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {

                for (i in indicatorViews.indices) {
                    indicatorViews[i]!!.isSelected = position == i
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

}